﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MineBoxRelease.Core;
using MineBoxRelease.Core.View;
using MineBoxRelease.Custom;
using DataFormats = System.Windows.DataFormats;
using Shortcut = MineBoxRelease.Model.Shortcut;

namespace MineBoxRelease.View
{
    /// <summary>
    /// AppBoxView.xaml 的交互逻辑
    /// </summary>
    public partial class AppBoxView : BaseView
    {
        private Boolean editable;
        private Border temp;
        private ShortcutItem movingItem;

        public AppBoxView(string title = null)
        {

            InitializeComponent();
            InitializeData();
            InitializeEvent();
            Title = title;
            if (title != null)
                tbTitle.Text = title;
        }

        //初始化变量
        private void InitializeData()
        {
            editable = false;
            temp = new Border { Width = 90, Height = 90 };
            viewer.AllowDrop = false;
        }

        //初始化事件
        private void InitializeEvent()
        {
            btnImport.Click += (s, e) => Import();
            btnEdit.Click += (s, e) => Edit();
            viewer.Drop += viewer_Drop;
            //pnList.MouseLeftButtonDown += pnList_MouseLeftButtonDown;
            pnList.MouseMove += pnList_MouseMove;
            pnList.MouseLeftButtonUp += pnList_MouseLeftButtonUp;
            pnList.MouseLeave += pnList_MouseLeave;
        }

        //双击启动程序
        private void ShortcutItem_DoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (editable) return;
            ShortcutItem item = sender as ShortcutItem;
            System.Diagnostics.Process.Start(item.Data.FilePath);
        }

        private void ShortcutItem_Removing(object sender, RoutedEventArgs e)
        {
            pnList.Children.Remove(sender as ShortcutItem);
        }

        void pnList_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ShortcutItem block = sender as ShortcutItem;
            if (!editable || block == null)
            {
                e.Handled = false;
                return;
            }
            MoveStart(block);
        }
        private void ShortcutItem_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ShortcutItem item = sender as ShortcutItem;
            if (!editable || item == null) return;
            MoveStart(item);
        }

        void pnList_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            Moving(e.GetPosition(pnList));
        }

        void pnList_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            MoveFinish();
        }

        void pnList_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            MoveFinish();
        }

        //图标拖入
        void viewer_Drop(object sender, System.Windows.DragEventArgs e)
        {
            string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            path = FileHelper.GetActualFilePath(path);
            string title = FileHelper.GetFileName(path);
            ShortcutItem item = new ShortcutItem(new Shortcut(title, path)) { Editable = true };
            pnList.Children.Add(item);
        }

        #region 功能
        public List<Shortcut> GetShortcuts()
        {
            List<Shortcut> list = new List<Shortcut>();
            foreach (ShortcutItem block in pnList.Children)
            {
                list.Add(block.Data);
            }
            return list;
        }

        public void SetShortcuts(List<Shortcut> list)
        {
            pnList.Children.Clear();
            foreach (Shortcut shortcut in list)
            {
                pnList.Children.Add(new ShortcutItem(shortcut));
            }
        }

        //导入文件夹
        private void Import()
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.ShowDialog();
            if (dialog.SelectedPath == null || dialog.SelectedPath.Equals("")) return;
            string selectedPath = dialog.SelectedPath;
            string[] fn = Directory.GetFiles(selectedPath);

            foreach (string s in fn)
            {
                string path = FileHelper.GetActualFilePath(s);
                string fileName = FileHelper.GetFileName(s);
                Shortcut model = new Shortcut(fileName, path);
                pnList.Children.Add(new ShortcutItem(model) { Editable = true });
            }

            if (btnEdit.Content.Equals("编辑"))
                Edit();
        }

        //编辑切换
        private void Edit()
        {
            if (btnEdit.Content.Equals("编辑"))
            {
                editable = true;
                btnEdit.Content = "保存";
                viewer.Draggable = false;
                viewer.AllowDrop = true;
            }
            else
            {
                editable = false;
                btnEdit.Content = "编辑";
                viewer.Draggable = true;
                viewer.AllowDrop = false;
                //if (pnList.Children.Count > 0)
                    ViewManager.Save(this);
            }

            foreach (var ele in pnList.Children)
            {
                ShortcutItem item = ele as ShortcutItem;
                if (item == null) continue;
                item.Editable = editable;
            }
        }

        //开始移动：加入临时项，移除真实项
        private void MoveStart(ShortcutItem item)
        {
            movingItem = item;
            temp.Background = new VisualBrush() { Visual = movingItem, Opacity = 0.5 };
            int index = pnList.Children.IndexOf(movingItem);
            pnList.Children.Insert(index, temp);
            pnList.Children.Remove(movingItem);
        }

        //移动中：更新临时项位置
        private void Moving(Point p)
        {
            if (!CanMove()) return;
            int index = (int)(Math.Floor(p.X / 90) + Math.Floor(p.Y / 90) * 6);
            int curIndex = pnList.Children.IndexOf(temp);
            if (index == curIndex) return;
            if (index > pnList.Children.Count - 1) index = pnList.Children.Count - 1;
            pnList.Children.Remove(temp);
            pnList.Children.Insert(index, temp);
        }

        //结束移动：移除临时项，还原真实项
        private void MoveFinish()
        {
            if (!CanMove()) return;
            int index = pnList.Children.IndexOf(temp);
            pnList.Children.Insert(index, movingItem);
            pnList.Children.Remove(temp);
            movingItem = null;
        }

        private Boolean CanMove()
        {
            if (!editable || movingItem == null) return false;
            return true;
        }
        #endregion
    }
}
